﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.API.Application.Command.UserInfoCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;

namespace RBAC_Uthorization.API.Application.CommandHandlers.UserInfoHandler
{
    public class USerInfoUpdateCommandHandlers : IRequestHandler<USerInfoUpdateCommand, ApiResult<int>>
    {
        private readonly IUserInfoRepository _userRepository;
        private readonly ILogger<USerInfoUpdateCommandHandlers> _logger;


        public USerInfoUpdateCommandHandlers(ILogger<USerInfoUpdateCommandHandlers> logger, IUserInfoRepository userRepository)
        {
            _logger = logger;
            _userRepository = userRepository;

        }

        public async Task<ApiResult<int>> Handle(USerInfoUpdateCommand request, CancellationToken cancellationToken)
        {

            try
            {
                var userlist = await _userRepository.GetAllAsync();
                var user = userlist.FirstOrDefault(x => x.sys_id == request.sys_id&&x.del_flag==0&&x.sys_id==request.sys_id&&x.offic_id==request.office_id);
                if (user == null)
                {
                    return new ApiResult<int>(ResultCode.NotFound, "用户不存在");
                }
                user.no = request.UpdateDto.no;
                user.name = request.UpdateDto.name;
                user.email = request.UpdateDto.email;
                user.phone = request.UpdateDto.phone;
                user.Sex = request.UpdateDto.Sex;
                user.avatar = request.UpdateDto.avatar;
                user.update_date = DateTime.UtcNow;
                user.update_by = request.Createby;
                var entity = await _userRepository.UpdateAsync(user);
                if (entity == null)
                {
                    return new ApiResult<int>(ResultCode.NotFound, "用户更新失败");
                }
                return new ApiResult<int>();
            }
            catch (Exception ex)
            {
                _logger.LogError($"用户更新失败:{ex.Message}->{ex.StackTrace}->{ex.InnerException}");
                return new ApiResult<int>(ResultCode.Fail, "用户更新失败");
            }

        }
    }
}
